package com.mes.bac.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mes.bac.backend.common.constant.ProcessStatus;
import com.mes.bac.backend.common.vo.R;
import com.mes.bac.backend.entity.Dispatch;
import com.mes.bac.backend.mapper.DispatchMapper;
import com.mes.bac.backend.service.IDispatchService;
import com.mes.bac.backend.service.IProductService;
import com.mes.bac.backend.service.IWorkstationService;
import com.mes.bac.backend.vo.DashboardStatsVO;
import com.mes.bac.backend.vo.WorkstationLoadVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Tag(name = "0. 仪表盘", description = "提供系统概览数据")
@RestController
@RequestMapping("/api/dashboard")
public class DashboardController {

    @Autowired
    private IProductService productService;

    @Autowired
    private IWorkstationService workstationService;

    @Autowired
    private IDispatchService dispatchService;

    @Autowired
    private DispatchMapper dispatchMapper;

    @Operation(summary = "获取核心统计数据")
    @GetMapping("/stats")
    public R<DashboardStatsVO> getStats() {
        DashboardStatsVO stats = new DashboardStatsVO();

        stats.setProductCount(productService.count());
        stats.setWorkstationCount(workstationService.count());

        QueryWrapper<Dispatch> waitingWrapper = new QueryWrapper<>();
        waitingWrapper.eq("status", ProcessStatus.WAITING.getCode());
        stats.setWaitingPieceCount(dispatchService.count(waitingWrapper));

        QueryWrapper<Dispatch> processingWrapper = new QueryWrapper<>();
        processingWrapper.eq("status", ProcessStatus.PROCESSING.getCode());
        stats.setProcessingPieceCount(dispatchService.count(processingWrapper));

        return R.success(stats);
    }

    @Operation(summary = "获取各工位任务负载")
    @GetMapping("/workstation-load")
    public R<List<WorkstationLoadVO>> getWorkstationLoad() {
        // 这个查询在数据量大时性能可能不高
        return R.success(dispatchMapper.getWorkstationLoad());
    }
}